package com.udima.reglocation.util;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.udima.reglocation.entities.UserSession;

public class UserSessionHandler {

	private static final String PREFS_ID = "com.udima.reglocation";

	private Context appContext;

	public UserSessionHandler(Context context) {
		this.appContext = context;
	}

	/**
	 * 
	 * @return
	 */
	public UserSession retrieveUserSession() {
		UserSession res = null;
		if (appContext != null) {
			SharedPreferences pref = appContext.getSharedPreferences(PREFS_ID, Activity.MODE_PRIVATE);
			if (pref != null) {
				
				String userId = pref.getString("userId", null);
				String sessionToken = pref.getString("sessionToken", null);
				//Long lastTimeUsed = pref.getLong("lastTimeUsed", 0);
				if(userId!=null && sessionToken!=null) {
					res = new UserSession();
					res.setUserId(userId);
					res.setSessionToken(sessionToken);
					//res.setLastTimeUsed(lastTimeUsed);
				}
			}
		}
		return res;
	}

	/**
	 * 
	 * @param session
	 */
	public void storeUserSession(UserSession session) {
		if (appContext != null) {
			SharedPreferences pref = appContext.getSharedPreferences(PREFS_ID, Activity.MODE_PRIVATE);
			if (pref != null) {
				Editor editor = pref.edit();

				// Almacenamiento del id del usuario y el token de la sesión en
				// las SharedPreferences
				editor.putString("userId", session.getUserId()); // jsonUserSession.getString("userId"));
				editor.putString("sessionToken", session.getSessionToken()); // jsonUserSession.getString("sessionToken"));
				//editor.putLong("lastTimeUsed", session.getLastTimeUsed()); //jsonUserSession.getString("lastTimeUsed"));

				// Guardado de los cambios en SharedPreferences
				editor.commit();
			}

		}
	}
}
